import CryptoJS from 'crypto-js'
export const cyptoTool = {
  data() {
    return {
      // 前后端定义的密钥，AES使用16位
      CRYPTOJSKEY: '64efac68cf074c8c',
      CRYPTOJSIV: '64efac68cf074c8c'
    }
  },

  methods: {
    // 加密
    encrypt(word) {
      const key = CryptoJS.enc.Utf8.parse(this.CRYPTOJSKEY)
      const iv = CryptoJS.enc.Utf8.parse(this.CRYPTOJSIV)
      const srcs = CryptoJS.enc.Utf8.parse(word)
      const encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
      return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
    },

    // 解密
    decrypt(word) {
      const key = CryptoJS.enc.Utf8.parse(this.CRYPTOJSKEY)
      const iv = CryptoJS.enc.Utf8.parse(this.CRYPTOJSIV)
      const base64 = CryptoJS.enc.Base64.parse(word)
      const srcs = CryptoJS.enc.Base64.stringify(base64)
      const decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
      const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
      return decryptedStr.toString()
    }
  }
}
